package com.telecom.at.man;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BasLogReader {
    public static void main(String [] args) {

        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "llyc";
        String password = "123456";
        StringBuffer sql = new StringBuffer();
        sql.append("insert into baslog" +
                "(account, interface, ipAddress, mac)" +
                "values(?,?,?,?)");
        Long num = 0L;
        int count = 0;
        String fileName = "BAS.log";

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = (Connection) DriverManager.getConnection(url, user, password);
            con.setAutoCommit(false);

            Long startTime = System.currentTimeMillis();
            PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());

            BufferedReader br = new BufferedReader(new FileReader(fileName));
            for(String line; (line = br.readLine()) != null; ) {

                String[] arrays = line.trim().split("\\s+");
                if(arrays.length == 5 && arrays[0].matches("^[0-9]*")) {

                    try {
                        Integer.parseInt(arrays[0]);
                        pst.setString(1, arrays[1]);
                        pst.setString(2, arrays[2]);
                        pst.setString(3, arrays[3]);
                        pst.setString(4, arrays[4]);
                        pst.addBatch();
                        num++;
                        if (num == 100000) {
                            pst.executeBatch();
                            con.commit();
                            num = 0l;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                }
            }

            pst.executeBatch();
            con.commit();
            Long endTime = System.currentTimeMillis();
            System.out.println("用时" + (endTime - startTime));
            pst.close();
            con.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
